package main

import (
	"embed"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
)

//go:embed all:frontend/dist
var assets embed.FS

func main() {
	// 设置日志文件
	logFile, err := setupLogging()
	if err != nil {
		log.Fatal(err)
	}
	defer logFile.Close()

	// 创建并运行应用
	if err := runApp(); err != nil {
		log.Printf("应用启动失败: %v", err)
		log.Fatal(err)
	}
}

// setupLogging 设置日志文件
func setupLogging() (*os.File, error) {
	// 确保日志目录存在
	logDir := "logs"
	if err := os.MkdirAll(logDir, 0755); err != nil {
		return nil, err
	}

	// 使用日期作为日志文件名
	currentTime := time.Now()
	logFileName := fmt.Sprintf("app_%s.log", currentTime.Format("2006-01-02"))
	logPath := filepath.Join(logDir, logFileName)

	// 创建或打开日志文件
	logFile, err := os.OpenFile(
		logPath,
		os.O_CREATE|os.O_WRONLY|os.O_APPEND,
		0666,
	)
	if err != nil {
		return nil, err
	}

	// 设置日志格式
	log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)

	// 同时输出到控制台和文件
	log.SetOutput(logFile)

	log.Printf("日志文件已创建: %s", logPath)
	return logFile, nil
}

// runApp 运行应用程序
func runApp() error {
	app := NewApp()

	return wails.Run(&options.App{
		Title:            "SSH免密配置工具",
		Width:            600,
		Height:           800,
		MinWidth:         600,
		MinHeight:        800,
		MaxWidth:         600,
		Assets:           assets,
		BackgroundColour: &options.RGBA{R: 248, G: 250, B: 252, A: 1},
		OnStartup:        app.startup,
		OnDomReady:       app.domReady,
		OnShutdown:       app.shutdown,
		WindowStartState: options.Normal,
		Frameless:        false,
		StartHidden:      false,
		AlwaysOnTop:      false,
		Bind: []interface{}{
			app,
		},
		// 添加调试选项
		Debug: options.Debug{
			OpenInspectorOnStartup: true,
		},
	})
}
